package club.emergency.wechat.department_staff.operate.provider.impl;

import club.emergency.wechat.common.excel.XlsExcelProcess;
import club.emergency.wechat.common.response.ResponseEntity;
import club.emergency.wechat.common.response.StatusCode;
import club.emergency.wechat.department_staff.operate.DepartmentStaffOperate;
import club.emergency.wechat.model.staff.DepartmentStaff;
import club.emergency.wechat.persistence.staff.DepartmentStaffMapper;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;

/**
 * Create with IntelliJ IDEA
 * Project Name: wechat
 * Package Name: club.emergency.wechat.staff.operate.provider.impl
 * Date: 2019/4/1
 *
 * @author: 快乐的小菌菌
 * Description:
 */
@RestController
public class DepartmentStaffOperateImpl implements DepartmentStaffOperate {

    private DepartmentStaffMapper departmentStaffMapper;

    private ExecutorService executorService;

    private PlatformTransactionManager platformTransactionManager;

    public DepartmentStaffOperateImpl(DepartmentStaffMapper departmentMapper, ExecutorService executorService, PlatformTransactionManager platformTransactionManager) {
        this.departmentStaffMapper = departmentMapper;
        this.executorService = executorService;
        this.platformTransactionManager = platformTransactionManager;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveDepartmentStaff(@RequestBody DepartmentStaff departmentStaff) {
        departmentStaffMapper.insert(departmentStaff);
        return ResponseEntity.ok(StatusCode.DB_SAVE_OK, "新增企业人员成功！", departmentStaff.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String modifyDepartmentStaff(@RequestBody DepartmentStaff departmentStaff) {
        departmentStaffMapper.updateById(departmentStaff);
        return ResponseEntity.ok(StatusCode.DB_MODIFY_OK, "修改企业人员信息成功！");
    }

    @Override
    public String saveDepartmentStaffFromExcel(@RequestParam("suffix") String suffix, @RequestBody byte[] bytes, @RequestParam("departmentId") Long departmentId, @RequestParam("departmentCode") String departmentCode) {
        Map<Integer, List<String>> process = XlsExcelProcess.process(suffix, bytes, false);
        List<DepartmentStaff> departmentStaffList = new ArrayList<>();
        for (int i = 2; i < process.size(); i++) {
            List<String> strings = process.get(i);
            if (strings.size() != 0) {
                if (strings.size() != 4) {
                    return ResponseEntity.error(StatusCode.EXCEL_ANALYSIS_ERROR, "Excel分析错误，第" + (i + 1) + "行数据不完整，请检查！");
                }
                String userName = strings.get(1);
                String staffNum = strings.get(2);
                String phone = strings.get(3);
                if (Objects.nonNull(userName) && Objects.nonNull(staffNum) && Objects.nonNull(phone)) {
                    DepartmentStaff departmentStaff = new DepartmentStaff();
                    departmentStaff.setUserName(userName);
                    departmentStaff.setStaffNum(staffNum);
                    departmentStaff.setPhone(phone);
                    departmentStaff.setDepartmentId(departmentId);
                    departmentStaff.setDepartmentCode(departmentCode);
                    departmentStaffList.add(departmentStaff);
                }
            }
        }
        executorService.execute(() -> {
            TransactionStatus transaction = platformTransactionManager.getTransaction(new DefaultTransactionDefinition());
            try {
                departmentStaffList.forEach(departmentStaff -> {
                    departmentStaff.setDepartmentId(departmentId);
                    departmentStaff.setDepartmentCode(departmentCode);
                    departmentStaffMapper.insert(departmentStaff);
                });
                platformTransactionManager.commit(transaction);
            } catch (Exception e) {
                platformTransactionManager.rollback(transaction);
            }
        });
        return ResponseEntity.ok(StatusCode.DB_SAVE_OK, "从Excel中企业人员分析成功！正在导入，请稍候查看。");
    }
}
